﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace checkFileSize
{
    public class ExcelTool
    {
        private XSSFWorkbook workbook;
        private string savePath;

        public ExcelTool()
        {

        }
    
        public ExcelTool(string savePath)
        {
            this.CreatExcel(savePath);
        }

        private XSSFWorkbook CreatExcel(string savePath)
        {
            //XSSFWorkbook workbook = null;
            if (savePath.LastIndexOf(".xlsx") > 0)  // 2007
            {
                this.workbook = new XSSFWorkbook();   // 2003
            }
            this.savePath = savePath;
            return this.workbook;
        }

        /// <summary>
        /// 创建excel 页数据
        /// </summary>
        public void CreatSheetData(List<List<string>> headers, List<List<string>> datas, string sheetName)
        {
            if (this.workbook == null)
            {
                return;
            }
            ISheet sheet;   // 配置表 sheet
            var appendRow = 0;   // 列

            sheet = this.workbook.CreateSheet(sheetName);  // 
            sheet.DefaultColumnWidth = 40;

            // 数据头插到数据前面
            datas.InsertRange(0, headers);

            foreach (List<string> values in datas)
            {
                var row = sheet.CreateRow(appendRow);
                var cellnum = 0;  // 行
                foreach (string value in values)
                {
                    var cell = row.CreateCell(cellnum);
                    cell.SetCellValue(value);
                    cellnum++;
                }
                appendRow++;
            }
        }

        /// <summary>
        /// 保存并输出当前excel
        /// </summary>
        public void SaveAllExcel()
        {
            if (this.workbook == null)
            {
                return;
            }
            FileStream fs = null;
            try
            {
                fs = new FileStream(this.savePath, FileMode.OpenOrCreate);
                if (fs.CanWrite)
                {
                    this.workbook.Write(fs);
                    this.workbook.Close();
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }

            }
            MessageBox.Show("导出完成");
        }
    }

}
